<template>
	<view class="add-record-container">
		<!-- 头部标题 -->
		<view class="header">
			<text class="subtitle">{{ currentCar.brand }} {{ currentCar.model }} ({{ currentCar.plateNumber }})</text>
		</view>

		<!-- 表单区域 -->
		<view class="form-container">
			<!-- 加油日期 -->
			<view class="form-item">
				<text class="label">加油日期</text>
				<picker mode="date" :value="form.refuelDate" @change="bindDateChange">
					<view class="picker-content">
						<text>{{ form.refuelDate || '请选择日期' }}</text>
						<uni-icons type="arrowdown" size="16" color="#999"></uni-icons>
					</view>
				</picker>
			</view>

			<!-- 当前里程 -->
			<view class="form-item">
				<text class="label">当前里程(km)</text>
				<input v-model="form.mileage" type="number" placeholder="请输入当前里程" class="input"
					placeholder-class="placeholder" @blur="validateMileage" />
			</view>

			<!-- 加油量 -->
			<view class="form-item">
				<text class="label">加油量(L)</text>
				<input v-model="form.oilVolume" type="number" placeholder="请输入加油量" class="input"
					placeholder-class="placeholder" @blur="validateOilVolume" />
			</view>

			<!-- 加油金额 -->
			<view class="form-item">
				<text class="label">加油金额(元)</text>
				<input v-model="form.amount" type="number" placeholder="请输入加油金额" class="input"
					placeholder-class="placeholder" @blur="calculateOilPrice" />
			</view>

			<!-- 油价 -->
			<view class="form-item">
				<text class="label">油价(元/L)</text>
				<input v-model="form.oilPrice" type="number" placeholder="请输入油价" class="input"
					placeholder-class="placeholder" @blur="calculateAmount" />
			</view>

			<!-- 加油站 -->
			<view class="form-item">
				<text class="label">加油站</text>
				<input v-model="form.gasStation" placeholder="可选填加油站名称" class="input" placeholder-class="placeholder" />
			</view>

			<!-- 备注 -->
			<view class="form-item">
				<text class="label">备注</text>
				<textarea v-model="form.remark" placeholder="可填写优惠信息等" class="textarea"
					placeholder-class="placeholder"></textarea>
			</view>

			<!-- 提交按钮 -->
			<button @click="submitForm" :disabled="!isFormValid"
				:class="['submit-btn', isFormValid ? 'active' : 'disabled']">
				提交记录
			</button>
		</view>
	</view>
</template>

<script>
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import {
		useStore
	} from 'vuex'
	import dayjs from 'dayjs'

	import {
		getCurrentInstance
	} from 'vue'

	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'



	// 查看当前页面栈
	export default {
		// 调试钩子顺序
		setup() {
			const recordId = ref('')
			const store = useStore()
			const currentCar = computed(() => store.state.currentCar)
			const isFormValid = ref(false)
			const {
				proxy
			} = getCurrentInstance()
			// 表单数据
			const form = ref({
				id: '',
				refuelDate: dayjs().format('YYYY-MM-DD'),
				mileage: '',
				oilVolume: '',
				amount: '',
				oilPrice: '',
				gasStation: '',
				remark: ''
			})


			onLoad((options) => {
				recordId.value = options.id || ''
				if (recordId.value) {
					loadData(recordId.value)
				}
			})

			const loadData = async (id) => {
				// 您的数据加载逻辑
				console.log("id=", id)
				const paramsId = {
					id: id
				}
				const res = await proxy.$api.getRecord(paramsId)
				if (res.code == 200) {
					form.id = res.data.id
					form.value.refuelDate = res.data.refuelDate
					form.value.mileage = res.data.mileage
					form.value.oilVolume = res.data.oilVolume
					form.value.amount = res.data.amount
					form.value.oilPrice = res.data.oilPrice
					form.value.gasStation = res.data.gasStation
					form.value.remark = res.data.remark
				}
			}

			// 验证里程
			const validateMileage = () => {
				if (form.value.mileage && parseFloat(form.value.mileage) <= 0) {
					uni.showToast({
						title: '里程必须大于0',
						icon: 'none'
					})
					return false
				}
				return true
			}

			// 验证加油量
			const validateOilVolume = () => {
				if (form.value.oilVolume && parseFloat(form.value.oilVolume) <= 0) {
					uni.showToast({
						title: '加油量必须大于0',
						icon: 'none'
					})
					return false
				}
				return true
			}

			// 计算油价
			const calculateOilPrice = () => {
				if (form.value.amount && form.value.oilVolume && !form.value.oilPrice) {
					form.value.oilPrice = (form.value.amount / form.value.oilVolume).toFixed(2)
				}
				checkFormValid()
			}

			// 计算金额
			const calculateAmount = () => {
				if (form.value.oilPrice && form.value.oilVolume && !form.value.amount) {
					form.value.amount = (form.value.oilPrice * form.value.oilVolume).toFixed(2)
				}
				checkFormValid()
			}

			// 选择日期
			const bindDateChange = (e) => {
				form.value.refuelDate = e.detail.value
				checkFormValid()
			}

			// 表单验证
			const checkFormValid = () => {
				const {
					refuelDate,
					mileage,
					oilVolume,
					amount
				} = form.value
				isFormValid.value = !!refuelDate && !!mileage && !!oilVolume && !!amount &&
					validateMileage() && validateOilVolume()
			}

			// 提交表单
			const submitForm = async () => {
				if (!isFormValid.value) return

				try {
					uni.showLoading({
						title: '提交中...',
						mask: true
					})

					// 格式化数据
					const params = {
						...form.value,
						id: form.id,
						mileage: parseFloat(form.value.mileage),
						oilVolume: parseFloat(form.value.oilVolume),
						amount: parseFloat(form.value.amount),
						oilPrice: form.value.oilPrice ? parseFloat(form.value.oilPrice) : null
					}
					const res = await proxy.$api.saveRecord(params)
					if (res.code === 200) {
						uni.showToast({
							title: '记录成功',
							icon: 'success'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					} else {
						throw new Error(res.message || '添加记录失败')
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '添加记录失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			}

			// 初始化数据
			onMounted(() => {
				checkFormValid()
			})

			return {
				currentCar,
				form,
				isFormValid,
				bindDateChange,
				validateMileage,
				validateOilVolume,
				calculateOilPrice,
				calculateAmount,
				submitForm
			}
		}
	}
</script>

<style scoped>
	.add-record-container {
		padding: 30rpx;
		background-color: #f8f8f8;
		min-height: 100vh;
	}

	.header {
		margin-bottom: 40rpx;
	}

	.title {
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
		display: block;
	}

	.subtitle {
		font-size: 28rpx;
		color: #666;
		margin-top: 10rpx;
		display: block;
	}

	.form-container {
		background-color: white;
		border-radius: 20rpx;
		padding: 30rpx;
	}

	.form-item {
		margin-bottom: 40rpx;
	}

	.label {
		font-size: 30rpx;
		color: #333;
		font-weight: 500;
		display: block;
		margin-bottom: 20rpx;
	}

	.picker-content {
		height: 80rpx;
		border: 1rpx solid #eee;
		border-radius: 8rpx;
		padding: 0 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.input,
	.textarea {
		width: 100%;
		border: 1rpx solid #eee;
		border-radius: 8rpx;
		padding: 20rpx;
		font-size: 30rpx;
	}

	.textarea {
		height: 180rpx;
	}

	.placeholder {
		color: #ccc;
	}

	.submit-btn {
		margin-top: 60rpx;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 45rpx;
		font-size: 32rpx;
		color: white;
	}

	.submit-btn.active {
		background-color: #7fbc8d;
	}

	.submit-btn.disabled {
		background-color: #ccc;
		opacity: 0.7;
	}
</style>